package com.example.education.service.impl;

import org.apache.mahout.cf.taste.common.Weighting;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.impl.neighborhood.NearestNUserNeighborhood;
import org.apache.mahout.cf.taste.impl.recommender.CachingRecommender;
import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.EuclideanDistanceSimilarity;
import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.neighborhood.UserNeighborhood;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.Recommender;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;

import java.io.File;
import java.util.List;

public class MyUserBasedRecommender {

    //ssm或者springboot框架中dataSource可通过@Autowire自动注入


    public List<RecommendedItem> userBasedRecommender(long userID, int size) {
        // step:1 构建模型 2 计算相似度 3 查找k紧邻 4 构造推荐引擎
        List<RecommendedItem> recommendations = null;
        List<RecommendedItem> recommendations1 = null;
        try {
            DataModel model = new FileDataModel(new File("static\\database.txt"));//构造数据模型
            UserSimilarity similarity = new PearsonCorrelationSimilarity(model, Weighting.WEIGHTED);//用PearsonCorrelation 算法计算用户相似度
            UserNeighborhood neighborhood = new NearestNUserNeighborhood(3, similarity, model);//计算用户的“邻居”，这里将与该用户最近距离为 3 的用户设置为该用户的“邻居”。
            Recommender recommender = new CachingRecommender(new GenericUserBasedRecommender(model, neighborhood, similarity));//采用 CachingRecommender 为 RecommendationItem 进行缓存
            recommendations = recommender.recommend(userID, size);//得到推荐的结果，size是推荐结果的数目

            List<RecommendedItem> recommendedItemList = recommender.recommend(5, 10);
            for (RecommendedItem recommendedItem : recommendedItemList) {
                System.out.println(recommendedItem);
            }

            DataModel model1 = new FileDataModel(new File("static\\database.txt"));//构造数据模型
            UserSimilarity similarity1 = new EuclideanDistanceSimilarity(model1);//用PearsonCorrelation 算法计算用户相似度
            UserNeighborhood neighborhood1 = new NearestNUserNeighborhood(3, similarity, model1);//计算用户的“邻居”，这里将与该用户最近距离为 3 的用户设置为该用户的“邻居”。
            Recommender recommender1 = new CachingRecommender(new GenericUserBasedRecommender(model1, neighborhood, similarity));//采用 CachingRecommender 为 RecommendationItem 进行缓存
            recommendations1 = recommender1.recommend(userID, size);
            recommendations.add((RecommendedItem) recommendations1);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return recommendations;
    }
}
